package cac.fenjian.resource.BZJReceive.rest;

import cac.fenjian.resource.BZJReceive.service.BZJReceiveService;
import cac.fenjian.resource.outStoreroom.sevice.OutStoreMaterialRoomService;
import cac.fenjian.resource.partreceivesearch.dao.PartReceiveDao;
import cac.fenjian.resource.tsuser.service.TsUserServiceImpl;
import com.alibaba.fastjson.JSON;
import com.cac.dme.adapter.rest.msg.PageParameter;
import com.cac.dme.adapter.rest.msg.QueryReqBean;
import com.cac.dme.adapter.rest.msg.QueryRespBean;
import com.cac.dme.adapter.rest.msg.ResponseMsg;
import lombok.extern.slf4j.Slf4j;
import net.logstash.logback.encoder.org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @className: BZJReceiveRest
 * @description: （描述这个类的作用）
 * @author: lqc
 * @date: 2023/5/26 10:03:03 周五
 * @version: 1.0
 */
@RestController
@Slf4j
@RequestMapping("/BZJReceiveRest")
public class BZJReceiveRest {
    @Autowired
    private TransactionDefinition transactionDefinition;
    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    @Autowired
    private BZJReceiveService bzjReceiveService;
    @Autowired
    private OutStoreMaterialRoomService outStoreMaterialRoomService;
    @Autowired
    private PartReceiveDao partReceiveDao;
    @Autowired
    private TsUserServiceImpl tsUserService;
    //待接收标准件查询，条件查询
    @PostMapping("/searchBZJCode")
    public ResponseMsg<QueryRespBean<HashMap>> searchBZJCode(@RequestBody Map map) {
        ResponseMsg<QueryRespBean<HashMap>> responseMsg = new ResponseMsg<>();


        String barcode =map.get("barcode").toString();
        String bzjCodeType=map.get("bzjCodeType").toString();
        //分页
        String param = JSON.toJSONString(map.get("pageParameter"));
        PageParameter pageParameter = JSON.parseObject(param, PageParameter.class);
        //查询条件
        String searchParamsParams = JSON.toJSONString(map.get("searchParams"));
        HashMap searchParams = JSON.parseObject(searchParamsParams, HashMap.class);

        QueryReqBean<HashMap> queryReqBean = new QueryReqBean<>();
        queryReqBean.setSearchParams(searchParams);
        queryReqBean.setPageParameter(pageParameter);

        //2023-08-18 yebo 判断是否需要直配
        if(map.containsKey("sendType")){
            if("Y".equals(map.get("sendType"))){
                //判断是否需要直配
                List<HashMap> rsl=partReceiveDao.searchIsDirectForBzj(barcode);
                if(rsl.size()>0){
                    return responseMsg.setMessage("当前条码："+barcode+"，存在日计划未配送，请到接收直配页面进行直配操作！").setRetCode("201");
                }
            }
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String account = (String) request.getSession().getAttribute("account");
        if (Objects.isNull(account)) {
            log.info("session过期，请重新登陆");
            responseMsg.setErrorDesc("账户已过期，请重新登录").setRetCode("201");
            return responseMsg;
        } else if ("admin".equals(account)) {
            return responseMsg.setRetCode("201").setErrorDesc("管理员账号无法完成操作，请切换登录用户");
        }
        String shop = (String)tsUserService.getUserInfoByAccount(account).get("shop");
        QueryRespBean<HashMap> result = bzjReceiveService.searchBZJCode(queryReqBean,barcode,bzjCodeType,shop);
        if(result.getResult().getTotal()>0){
            responseMsg.setMessage("扫码成功").setRetCode("200");
        }else {
            responseMsg.setMessage("当前物料未移交或已接收，或所属单位与当前操作人不同！").setRetCode("201");
        }
        responseMsg.setResponseBody(result);
        return responseMsg;
    }

    /***
     * 标准件扫码接收叫箱
     * */
    @PostMapping("bzjScanRecive")
    public ResponseMsg<String> bzjScanRecive(@RequestBody HashMap map){
        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        String IP=null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        String receiveEmpCode = (String) request.getSession().getAttribute("account");
        if(Objects.isNull(receiveEmpCode)){
            responseMsg.setRetCode("201");
            responseMsg.setMessage("登录过期，请重新登录！");
            return responseMsg;
        }
        //事务管理
        TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            List<HashMap> lists = (List<HashMap>) map.get("data");
            for(HashMap data :lists){
                //改变接收状态
                bzjReceiveService.changeTransferType4Bzj((String)data.get("wmsDeliveryPlanId"),receiveEmpCode,IP);
            }
            //调用零件缓存箱出库
            responseMsg = outStoreMaterialRoomService.callBzjBox(lists,IP);
            if(responseMsg.getRetCode().equals("201")){
                platformTransactionManager.rollback(transaction);
                return responseMsg;
            }
            //全部成功提交事务
            platformTransactionManager.commit(transaction);
            return responseMsg;
        }catch (NullPointerException ne){
            ne.printStackTrace();
            platformTransactionManager.rollback(transaction);
            return responseMsg.setRetCode("201").setMessage("叫箱失败！请确认是否还有空箱！");
        }catch (Exception e){
            e.printStackTrace();
            platformTransactionManager.rollback(transaction);
            return responseMsg.setRetCode("201").setMessage("接收失败").setErrorDesc(ExceptionUtils.getFullStackTrace(e));
        }
    }
}
